package com.wy2cloud.core.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wy2cloud.core.tools.StringTools;

/**
 * cookie工具集
 * @author admin
 *
 */
public final class CookieTools {

	public static void addCookie(HttpServletResponse response,String name,String value,int maxAge) {
		addCookie(response, name, value, maxAge,null,null);
	}
	public static void addCookie(HttpServletResponse response,String name,String value,int maxAge,String domain,String path){
	    Cookie cookie = new Cookie(name,value);
	    if(StringTools.isEmpty(path)) {
	    	cookie.setPath("/");
	    }else {
	    	cookie.setPath(path);
	    }
	    if(!StringTools.isEmpty(domain)) {
	    	cookie.setDomain(domain);
	    }	    
	    if(maxAge>0)  cookie.setMaxAge(maxAge);
	    response.addCookie(cookie);
	}
	
	/**
	 * 取cookie值
	 * @param request
	 * @param cookieName
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request,String cookieName) {
		Cookie cookie=getCookie(request, cookieName);
		if(cookie!=null) {
			return cookie.getValue();
		}
		return StringTools.Empty;
	}
	
	public static void setCookie(HttpServletRequest request,HttpServletResponse response,String cookieName,String value,int maxAge,String domain,String path) {
		Cookie cookie=getCookie(request, cookieName);
		if(cookie!=null) {
			cookie = new Cookie(cookieName,value);
		}
		if(StringTools.isEmpty(path)) {
	    	cookie.setPath("/");
	    }else {
	    	cookie.setPath(path);
	    }
	    if(!StringTools.isEmpty(domain)) {
	    	cookie.setDomain(domain);
	    }	    
	    if(maxAge>0)  cookie.setMaxAge(maxAge);
	    response.addCookie(cookie);
	}
	
	private static Cookie getCookie(HttpServletRequest request,String cookieName) {
		if(StringTools.isEmpty(cookieName)) return null;
		Cookie[] cookies = request.getCookies();
		if(cookies==null) return null;
		for (Cookie cookie : cookies) {
			if(cookie.getName().equals(cookieName)) {
				return cookie;
			}
		}
		return null;
	}
}
